package com.genius.framework.multitenancy.service;

import com.genius.framework.multitenancy.client.ScheduleTaskClient;
import feign.Feign;
import feign.FeignException;
import feign.Target;
import feign.codec.Decoder;
import feign.codec.Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.openfeign.FeignClientsConfiguration;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
@Import(FeignClientsConfiguration.class)
public class ScheduleTaskClientService {

    @Value("${schedule.task.service.address.prefix}")
    private String addressPrefix;

    private ScheduleTaskClient scheduleTaskClient;

    @Autowired
    public ScheduleTaskClientService(Decoder decoder, Encoder encoder) {
        scheduleTaskClient = Feign.builder()
                //.client(client)
                .encoder(encoder)
                .decoder(decoder)
                .target(Target.EmptyTarget.create(ScheduleTaskClient.class));
    }

    public List<Map<String, String>> getCommonScheduleTaskBean(String serviceName) throws URISyntaxException {
        List<Map<String, String>> beans = new ArrayList<>();
        String url = addressPrefix + "/" + serviceName;
        try {
            beans = scheduleTaskClient.getCommonScheduleTaskBean(new URI(url));
        } catch (FeignException e) {
            if (e.status() == 404) {
                return beans;
            }
            e.printStackTrace();
        }
        return beans;
    }

    public List<Map<String, Object>> getCommonScheduleTaskMethod(String serviceName, String className) throws URISyntaxException {
        List<Map<String, Object>> methods = new ArrayList<>();
        String url = addressPrefix + "/" + serviceName;
        try {
            methods = scheduleTaskClient.getCommonScheduleTaskMethod(new URI(url), className);
        } catch (FeignException e) {
            if (e.status() == 404) {
                return methods;
            }
            e.printStackTrace();
        }
        return methods;
    }
}
